const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')

// 创建Token
const signToken = (user) => {
  // 私钥
  const privateKey = fs.readFileSync(path.join(__dirname, '../secretKeys/rsa_private_key.pem'))
  const params = {
    ...user,
    _id: user._id,
  }
  return jwt.sign(params, privateKey, { algorithm: 'RS256', expiresIn: '2h' })
}

// 校验Token
const verifyToken = (token) => {
  // 公钥
  const publicKey = fs.readFileSync(path.join(__dirname, '../secretKeys/rsa_public_key.pem'))
  try {
    return jwt.verify(token, publicKey)
  } catch (err) {
    // 处理非法token、过期token等问题
    return null
  }
}

module.exports = {
  signToken,
  verifyToken,
}
